<? require("adm_header.php"); ?>
<? writeCommonAdminTable("User Administration",1);?>


<a href="javascript:history.go(-1)">Back</a>


<?
$user_id=getParamInt("user_id","");
$mainType=getParamInt("mainType",0);
$package_id = getParamInt("addPid",-1);
$isPackage = getParamInt("isPackage",0);
if($isPackage!=1) $package_id = -1;
/*if( $package_id != 0 && $mainType==0){
	$aux = getPackageinfo($package_id);
	$mainType = $aux['mainType'];
}
if($mainType==0)
	$mainType = ID_CAT_COMPRA;*/


if (getParam("delete",""))
{
	if (delete_user("$user_id"));
	{
		echo "<b>User deleted</b><br />";
		echo "User " . getParam("user_name","") ." was deleted successfully.<br /><br />";
		writeCommonAdminTable("","2");
		require("admfooter.php"); 
		exit;
	}

}

if (getParam("editpay",""))
{
	/*$sql="update $user_credits set ";
	$sql.="pay_membership_expire=" . getParam("pay_membership_expire",0);
	$sql.=",pay_credits=" . getParam("pay_credits",0);
	$sql.=",pay_bold=" . getParam("pay_bold",0);
	$sql.=",pay_upload=" . getParam("pay_upload",0);
	$sql.=",pay_upload_video=" . getParam("pay_upload_video",0);
	$sql.=",pay_vendor=" . getParam("pay_vendor",0);
	$sql.=",user_is_vendor=" . getParam("pay_vendor",0);
	$sql.=",pay_premium=" . getParam("pay_premium",0);
	$sql.=" where user_id=" . getParam("user_id","");
	$res_update=q($sql);*/
	//q("delete from $user_credits where user_id=".getParamInt("user_id","")." and mainType=".getParamInt("mainType","")." and package_id=");
	$flagExiste = false;
	$resExistsCreits = q("select count(*) from $user_credits where user_id=".getParamInt("user_id","")." and mainType=".getParamInt("mainType","")." and package_id=".$package_id);
	if($rowExists = mysql_fetch_row($resExistsCreits))
	{
		if($rowExists[0]>0)
			$flagExiste = true;
	}
	
	$actionType = "";
	
	if(!$flagExiste){
		$sql="insert into $user_credits(`user_id`,`pay_membership_expire`,`pay_credits`,`pay_bold`,`pay_num_images`,`pay_upload`,
										`pay_vendor`,`pay_premium`,`pay_upload_video`,`package_id`,`mainType`) values(";		
		$sql.=getParamInt("user_id","");
		$sql.=",".addDaysToTimeStamp(getParamInt("pay_membership_expire",0),time());
		$sql.=",".getParamInt("pay_credits",0);
		$sql.=",".getParamInt("pay_bold",0);
		$sql.=",".getParamInt("pay_upload",0);	
		$sql.=",".getParamInt("pay_upload",0);
		$sql.=",".getParamInt("pay_vendor",0);
		$sql.=",".getParamInt("pay_premium",0);
		$sql.=",".getParamInt("pay_upload_video",0);
		$sql.=",".getParamInt("addPid",0);
		$sql.=",".getParamInt("mainType",0).");";
		
		$actionType="creo";
		
	}else{
		$sql="update $user_credits set ";
		$sql.=" pay_membership_expire=".addDaysToTimeStamp(getParamInt("pay_membership_expire",0),time());
		$sql.=" ,pay_credits=".getParamInt("pay_credits",0);
		$sql.=" ,pay_bold=".getParamInt("pay_bold",0);
		$sql.=" ,pay_num_images=".getParamInt("pay_upload",0);	
		$sql.=" ,pay_upload=".getParamInt("pay_upload",0);
		$sql.=" ,pay_vendor=".getParamInt("pay_vendor",0);
		$sql.=" ,pay_premium=".getParamInt("pay_premium",0);
		$sql.=" ,pay_upload_video=".getParamInt("pay_upload_video",0);
		$sql.=" where package_id=".getParamInt("addPid",0)." and mainType=".getParamInt("mainType",0)." and user_id=".getParamInt("user_id","");
		
		$actionType="actualizo";
		
	}
	$res_update=q($sql);
	
		echo "<br/><p><font color=\"green\">El credito se $actionType de manera correcta</font></p>";
}

if ($banid)
{
				$sql_ban = "update $usr_tbl set user_status = 1 where user_email = '$banid'";
            	$result = mysql_query($sql_ban);
            	print "<hr /> User $banid has been blocked from login. <hr />";	
}
if ($unbanid)
{
				$sql_ban = "update $usr_tbl set user_status = '' where user_email = '$unbanid'";
            	$result = mysql_query($sql_ban);
            	print "<hr /> User $unbanid has been activated. <hr />";	
}
if ($delapp)
{
				$sql_ban = "update $usr_tbl set user_approved = 0 where user_email = '$userid'";
            	$result = mysql_query($sql_ban);
            	print "<hr /> User $userid is now marked as <i>not approved yet</i> member. <hr />";	
}
/**
 * Botón de "habilitar/deshabilitar" los anuncios del usuario
 * que hayan sido dados de alta con el paquete "Concesionara
 * Virtual"
 */
$concesionariaVirtualMuestra=getParam('concesionariaVirtualMuestra',NULL);
if ($concesionariaVirtualMuestra=='t'||$concesionariaVirtualMuestra=='f'){
	if ($concesionariaVirtualMuestra=='t'){
		$enable='1';
		$cantidad='32767';
	}else{
		$enable='0';
		$cantidad='0';
	}
	
	$sql_concesionariaVirtualMuestra="update mvial_ad set ad_enabled={$enable} where ad_package_id=121 and ad_owner={$user_id}";
	$result = mysql_query($sql_concesionariaVirtualMuestra);

	$sql_concesionariaVirtualPaquete="	update mvial_user_credits set	pay_credits={$cantidad},
																		pay_num_images={$cantidad},
																		pay_upload={$cantidad}
										where package_id=121 and user_id={$user_id}";
	$result = mysql_query($sql_concesionariaVirtualPaquete);
	
	print "<hr />Los anuncios de Concesionaria virtual se han";
	if ($concesionariaVirtualMuestra=='t')print " mostrado";
	else print " ocultado";
	print ".<hr />";
}


/***********Agregar paquete nuevo****/
if (getParam("addSubmit",""))
{
	$paquete = getPackageinfo(getParam("addPid",0));
	
	addPackage(getParam("user_id",""),getParam("addPid",""));	
	//JMR: Agregado el parametro extra que indica la cantidad de paquetes
	$oid=makeOrder(getParam("addPid",""),getParam("user_id",""),time(),getParam("addPrice","0"),1);
	$status = 'Paid';
	if(getParam("addPrice",0)== 0){
		$status = 'Regalo';	
	}
	completeOrder($oid,$status,999,getParam("addPrice","0"),getParam("addPid",""));	
	echo "<br/><p><font color=\"green\">Orden completa</font></p>";
	
	$lNewUserVerifyArray=array($name,$paquete['pname'],getMainTypeName($paquete['mainType']),"http://$set_url/member_login.php");
	if($status == 'Regalo'){
		$lSubject = LA_MAIL_CREDITS_FREE_SUBJECT;
	}else{
		$lSubject = LA_MAIL_CREDITS_PAYED_SUBJECT;
	}
	$lBody = formatString(LA_MAIL_CREDITS_FREE_BODY, $lNewUserVerifyArray);		
	
}
/**********************************/
if(getParam("addSubmit","")==""){
	
	$result;

	if($package_id != -1){
		$result = q("select A.*,B.`pay_membership_expire`,B.`pay_credits`,B.`pay_bold`,B.`pay_num_images`,B.`pay_upload`,
			B.`pay_wysiwyg`,B.`pay_vendor`,B.`pay_premium`,B.`pay_upload_video`,B.`mainType` 
			from $usr_tbl A left join $user_credits B ON A.user_id=B.user_id 
			where A.user_id =$user_id and B.mainType=$mainType and B.package_id=$package_id ");
	}else{
		$result = q("select A.*,0 as `pay_membership_expire`,0 as `pay_credits`,0 as `pay_bold`,0 as `pay_num_images`,0 as `pay_upload`,
			0 as `pay_wysiwyg`,0 as `pay_vendor`,0 as `pay_premium`,0 as `pay_upload_video`,0 as `mainType` 
			from $usr_tbl A where A.user_id =$user_id ");
	}

	
}else{
	$result = q("select A.* from $usr_tbl A where A.user_id =$user_id"); 
	
}


$numrows=mysql_num_rows($result);
$row = mysql_fetch_array($result);
$userid = $row["user_email"];
$name = $row["user_name"];
$email = $row["user_email"];
$registered  = $row["user_date"];
$num_ads = $row["user_num_ads"];
$num_logged = $row["user_num_login"];
$num_contacted = $row["user_contacted"];
$credits = $row["user_credits"];
$registered = formatDateShort($row["user_date"]);
$last_login = formatDateShort($row["user_date_last_login"]);
$status = $row["user_status"];
//$verify = $row["uverify"];
$months = $row["months"];
$user_approved = $row["user_approved"];
$user_pass_plain = $row["user_pass_plain"];
$pay_membership_expire = $row["pay_membership_expire"];
$pay_membership_expire_h=formatDateShort($pay_membership_expire);
$pay_credits = $row["pay_credits"];
$pay_bold = $row["pay_bold"];
$pay_upload = $row["pay_upload"];
$pay_upload_video = $row["pay_upload_video"];
$pay_vendor = $row["pay_vendor"];
$pay_premium = $row["pay_premium"];

/** Mandamos el email al usuario acá para notificarle del credito, despues de haber obtenido su dirección ***/
if (getParam("addSubmit",""))
{
	if(isset($lSubject) && isset($lBody))
		sendEmail($email, $set_webmaster_address, $lSubject, $lBody, "",false);
	else
		echo "No están seteadas las variables: lSubject y lBody\n"		;
}

if (!$pay_membership_expire_h)
	$pay_membership_expire_h="Never";

if (!$num_ads)	
	$num_ads=0;
if (!$num_logged)	
	$num_logged=0;
if (!$num_contacted)	
	$num_contacted=0;
echo "<br /><br /><b>Username/email:</b><br />$name (<a href='mailto:$email'>$email</a>)";

echo "<br /><br /><b>Some Stats:</b><br />";
echo "<table class='noBorder' width='300'>";
echo "<tr><td>Last login:</td><td>$last_login</td><td></td><td>Num ads:</td><td><a href='adm_classifieds_list.php?ads_by_user=$user_id'>$num_ads</a></td></tr>";
echo "<tr><td>Registered</td><td>$registered</td><td></td><td>Logged in:</td><td>$num_logged</td></tr>";
echo "<tr><td>Expires:</td><td>$pay_membership_expire_h</td><td></td><td>Contacted:</td><td>$num_contacted</td></tr>";
echo "</table>";

print "<br /><br /><b>Status:</b><br />";

if ($approve_mem)
{
	if ($user_approved==0)
		echo "<font color='red'>This user is awaiting your approval</font><br />";	
	elseif ($user_approved==1)
		print "<font color='green'>User is approved by you</font><br />";	
}

if ($set_opt_verify)
{
	if ($user_pass_plain !="")
		echo "<font color='red'>User has not yet clicked the activation link</font><br />";	
	else
		echo "<font color='green'>User has clicked the activation link</font><br />";	
}

if ($status == 1)
	echo "This user is blocked from login by your request (admin).<br />";	
elseif ($approve_mem AND $approve)
	echo "All privileges.<br />";	
elseif (!$approve_mem)
	echo "All privileges.<br />";	



print "<p /><b>Options:</b><br />
<a href='adm_user.php?user_id=$user_id&delete=1&user_name=$name'>Delete user</a><br />
<a href='adm_block.php?user_id=$user_id&user_name=$email'>Block user</a><br />
<!--
<a href='adm_user.php?banid=$email&amp;email=$email'>Ban user</a><br />
<a href='adm_user.php?unbanid=$email&amp;email=$email'>UnBan user</a><br />
<a href='adm_user.php?userid=$email&amp;delapp=1&amp;email=$email'>Remove approval</a><br />
<a href='adm_user.php?email=$email&amp;credituseridsubtract=$email'>Remove one credit</a>--><br />";
/** JMR: Seccion agregada para mostrar los diferentes paquetes de creditos del usuario *******/
echo "<br /><b>Paquetes de usuario</b>";
$mainTypeCurrent=-1000;
$resultsPaquetes = q("SELECT pay_membership_expire,pay_credits,pay_bold,pay_num_images,pay_upload,pay_vendor,pay_premium,pay_upload_video,m.mainType,n.pname,n.pid".
					 " FROM mvial_user_credits m left join mvial_packages n on m.package_id=n.pid where user_id=$user_id order by m.mainType");
echo "<table style=\"border: 1px;\">
		<thead>
			<tr>
				<th><small>Nombre</small></th>
				<th><small>Avisos</small></th>
				<th><small>Destacado</small></th>
				<th><small>Imagenes</small></th>
				<th><small>Consesionaria</small></th>
				<th><small>Videos</small></th>			
				<th><small>Expira</small></th>
				<th><small>Acciones</small></th>
			</tr>
		</thead>
		<tbody>";
while($row = mysql_fetch_array($resultsPaquetes)){
	
	if($mainTypeCurrent!=$row["mainType"]){		
		$mainTypeCurrent=$row["mainType"];		
		echo "<tr class=\"alt\"><td colspan=\"8\" style=\"text-align:left;\"><strong>".getMainTypeName($mainTypeCurrent)."</strong></td></tr>";
	}
	
		$name=$row["pname"];
		$expira = formatDateShort($row["pay_membership_expire"]);
		$pid=$row["pid"];
		if(empty($name)){
				$name=EF_GIF;
				$expira="ilimitado";
		}		
		if(!isset($pid)) $pid = 0;
		echo "<tr>".
				"<td>".$name."</td>".
				"<td>".$row["pay_credits"]."</td>".
				"<td>".$row["pay_bold"]."</td>".
				"<td>".$row["pay_num_images"]."</td>".
				"<td>".$row["pay_vendor"]."</td>".
				"<td>".$row["pay_upload_video"]."</td>".
				"<td>".$expira."</td>".
				"<td><a href=\"adm_user.php?user_id=".$user_id."&mainType=".$row["mainType"]."&addPid=".$pid."&isPackage=1#modif_credits\" >modificar</a></td>".
			  "</tr>";

}
echo "</tbody></table>";
/** END JMR ****************************************/

/**
 * Botón de "habilitar/deshabilitar" los anuncios del usuario
 * que hayan sido dados de alta con el paquete "Concesionara
 * Virtual"
 */
$foo=q("select count(1) as c from mvial_user_credits where user_id={$user_id} and package_id=121");
$foo=mysql_fetch_array($foo);
if ($foo['c']){
?>
	<br />
	<b>Anuncios emitidos con Concesionaria Virtual:</b><br />
	-<a href='adm_user.php?user_id=<?=$user_id?>&concesionariaVirtualMuestra=t'>Mostrar</a>-
	||
	-<a href='adm_user.php?user_id=<?=$user_id?>&concesionariaVirtualMuestra=f'>Ocultar</a>-
	<br />
<?
}
echo "<br /><b>Payment History</b>";
echo "<table class='noBorder' width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>";
echo "<td>Package</td><td>Ordered</td><td>Price</td><td>Vendor</td><td>Status</td></tr>";

$sql = "select * from $pay_tbl where o_user='" . getParamInt("user_id","") . "' order by o_date desc limit 10";
$res_1 = q($sql);
while ($row = mysql_fetch_array($res_1))
{
	 	
 	$sql = "select * from $pkg_tbl where pid=" . $row["o_package"];
	$res=q($sql);
	$row_pkg = mysql_fetch_array($res);
	$pkg_name=$row_pkg["pname"];	
	$o_vendor=$row["o_vendor"];	
	
	if ($o_vendor==98)
		$o_vendor="Check/Bank";
		
	if ($o_vendor==999)
		$o_vendor="Manual";

	if (!$row["o_date_paid"])	
		$lPaid="<span class='red'>Not paid</span>";
	else
		$lPaid=formatDateShort($row["o_date_paid"]);	
	echo "<tr><td><a href='adm_package_edit.php?pid=".$row["o_package"]."'>". $pkg_name . "</a></td><td>" . formatDateShort($row["o_date"]) . " </td><td>" . $row["o_amount"] . "</td><td>$o_vendor</td><td>" . $row["o_status"] . " ". $lPaid ."</td></tr>";

}

echo "</table>";
	
echo "<br /><b>Manual Payment</b>";
echo "<br /><small>If you want to give a gift to a friend or show goodwill, you may use this. <br />Package will get status 'Paid' imidiatly and is recored as an completed order.</small>";
echo "<form method='post' action='adm_user.php'>";
$sql="select * from $pkg_tbl";
$r=q($sql);
echo "<select name='addPid'>";
while ($row=mysql_fetch_array($r))
{
	echo "<option value='".$row["pid"]."'>". $row["pname"] . " (" . $row["pprice"]  . ")</option>";	
}
echo "</select>";
echo "&nbsp;&nbsp;Price: ";
echo "<input type='text' name='addPrice' value='0'>";

echo "<input type='hidden' name='user_id' value='".getParam("user_id","") . "'>";
echo "&nbsp;&nbsp;<input type='submit' name='addSubmit' value='Add Package'>";
echo "</form>";
echo "<p><b>NOTA: para que los creditos sean reconocidos como creditos de regalo, dejen en 0 (cero) el campo 'Price' </b></p>";


if($package_id!=-1){
		echo "<span id=\"modif_credits\"></span>";
		echo "<br /><b>Correct User Credits</b>";
		echo "<br /><small>This will manually change a users permission. Anything you do here will not be recored as payment or an order. <br />Use it if a user has experienced technical problems and needs to be awared credits.</small>";
		echo "<form method='post' action='adm_user.php'>";
		echo "<table class='noBorder'>";
		/*echo "<tr><td>Tipo de Paquete:</td><td>";
		echo '<select name="addPid">';
		$r=q($sql." order by mainType");
		while ($row=mysql_fetch_array($r))
		{
			echo "<option value='".$row["pid"]."'>".'<b>'.getMainTypeName( $row["mainType"]).'</b> - '.$row["pname"]  ." (" . $row["pprice"]  . ")</option>";	
		}
		echo "</select>";
		echo "</td></tr>";*/
		/*echo "<tr><td>Tipo de Credito:</td><td>
				<select name=\"mainType\" onchange=\"location = 'adm_user.php?user_id=".getParam("user_id","")."&mainType='+this.options[this.selectedIndex].value+'&addPid=0';\">";
		echo		"<option value=\"".ID_CAT_COMPRA."\"    ";if( $mainType==ID_CAT_COMPRA || $mainType==0)  echo "selected=\"selected\""; echo ">Compra</option>";
		echo		"<option value=\"".ID_CAT_ALQUILER."\"  ";if( $mainType==ID_CAT_ALQUILER)  echo "selected=\"selected\""; echo ">Alquiler</option>";
		echo		"<option value=\"".ID_CAT_SERVICIOS."\" ";if( $mainType==ID_CAT_SERVICIOS) echo "selected=\"selected\""; echo ">Servicios</option>";
		echo		"<option value=\"-1\"                   ";if( $mainType==-1) echo "selected=\"selected\""; echo ">Compra:Desmantelados</option>";
		echo		"</select></td></tr>";*/
		echo "<tr><td>Tipo de Credito:</td><td>";
		echo "<strong>".getMainTypeName($mainType)."</strong>";
		echo "</td></tr>";
		echo "<tr><td>Pay Avisos:</td><td><input type='text' name='pay_credits' value='$pay_credits' size='2'></td></tr>";
		echo "<tr><td>Duración del aviso:</td><td><input type='text' name='pay_membership_expire' size='10' value='";
		if($package_id==0)
			echo "0";
		else
			echo round(($pay_membership_expire-addDaysToTimeStamp(0,time()))/(60*60*24));
		echo "'>";
		echo " <small> dias desp de hoy en vencerá el credito</small>";
		echo "</td></tr>";
		echo "<tr><td>Pay Bold:</td><td><input type='text' name='pay_bold' value='$pay_bold' size='2'></td></tr>";
		echo "<tr><td>Pay Premium:</td><td><input type='text' name='pay_premium' value='$pay_premium' size='2'></td></tr>";
		echo "<tr><td>Pay Image Upload:</td><td><input type='text' name='pay_upload' value='$pay_upload' size='2'></td></tr>";
		echo "<tr><td>Pay Video Upload:</td><td><input type='text' name='pay_upload_video' value='$pay_upload_video' size='2'></td></tr>";
		
		echo "<tr><td>Pay Vendor:</td><td><input type='text' name='pay_vendor' value='$pay_vendor' size='2'></td></tr></table>";
		echo "<input type='hidden' name='user_id' value='".getParam("user_id","") . "'>";
		echo '<input type="hidden" name="addPid" value="'.$package_id.'">';
		echo '<input type="hidden" name="isPackage" value="1">';
		echo '<input type="hidden" name="mainType" value="'.$mainType.'">';
		echo "&nbsp;&nbsp;<input type='submit' name='editpay' value='Update'>";
		echo "</form>";
}
writeCommonAdminTable("","2");
require("adm_footer.php"); ?>
